package com.king.base.auth.utils;

import cn.hutool.json.JSONObject;
import com.king.base.auth.security.JwtUser;
import com.king.base.msg.expection.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 获取当前登录的用户
 * @author TianYZ
 * @date 2019-01-17
 */
public class SecurityUtils {

    public static UserDetails getUserDetails() {
        UserDetails userDetails = null;
        try {
            userDetails = (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录状态过期");
        }
        return userDetails;
    }

    /**
     * 获取系统用户登录名
     * @return 系统用户登录名
     */
    public static String getUsername(){
        Object obj = getUserDetails();
        JSONObject json = new JSONObject(obj);
        return json.get("loginName", String.class);
    }

    /**
     * 获取系统用户id
     * @return 系统用户id
     */
    public static String getUserId(){
        Object obj = getUserDetails();
        JSONObject json = new JSONObject(obj);
        return json.get("userId", String.class);
    }

    /**
     * 获取登录用户名
     * @return 登录用户名
     */
    public static String getName(){
        Object obj=getUserDetails();
        JSONObject json = new JSONObject(obj);
        return json.get("username",String.class);
    }

    /**
     * 获取登录用户所在部门
     * @return 登录用户部门ID
     */
    public static String getDeptId(){
        Object obj=getUserDetails();
        JSONObject json = new JSONObject(obj);
        return json.get("deptId",String.class);
    }

    public static JwtUser getCurrentUser(){
        JwtUser user=(JwtUser)getUserDetails();

        return user;
    }
}
